// @ts-check
import { existsSync, promises } from "node:fs";
import { join } from "node:path";
import postcss from "postcss";
import { p2 } from "../../shared/p2.mjs";

/**
 * @production
 */
// const CssFileName = "process.css";
// const CssOutFileName = "process.out.css";
// const CssOutMapFileName = `${CssOutFileName}.map`;

// 处理 CSS
/**
 * @description 处理 CSS 文件，可选是否生成 source map。
 * @param {boolean=} sourceMap 是否生成 source map。
 * @returns {Promise<void>}
 */
async function processCSS(sourceMap = false) {
  /**
   * @type {string}
   */
  let css;
  try {
    // 读取 CSS 文件
    css = await promises.readFile(p2("postcss/process.css"), "utf8");
  } catch (error) {
    console.error("❌ 读取 CSS 文件时出错:", error);
    return;
  }
  try {
    console.log("🚀 开始处理 CSS...");

    // 使用 PostCSS 处理
    const result = await postcss().process(css, {
      from: p2("postcss/process.css"),
      to: p2("postcss/dist/process.out.css"),
      map: { inline: false, annotation: sourceMap },
    });

    // 确保 dist 目录存在
    if (!existsSync(p2("postcss/dist"))) {
      await promises.mkdir(p2("postcss/dist"), {
        recursive: true,
      });
    }

    // 写入处理后的 CSS
    await promises.writeFile(p2("postcss/dist/process.out.css"), result.css);

    // 如果需要 source map
    if (sourceMap && result.map) {
      await promises.writeFile(
        p2("postcss/dist/process.out.css.map"),
        result.map.toString(),
      );
      console.info(
        `📁 输出 source map 文件: ${p2("postcss/dist/process.out.css.map")}`,
      );
    }

    console.info("✅ CSS 处理完成!");
    console.info(`📁 输出文件: ${p2("postcss/dist/process.out.css")}`);

    // 显示一些统计信息
    const originalSize = Buffer.from(css).length;
    const processedSize = Buffer.from(result.css).length;
    console.log(`📊 文件大小: ${originalSize} bytes → ${processedSize} bytes`);
  } catch (error) {
    console.error("❌ 处理 CSS 时出错:", error);
  }
}

// 运行处理
processCSS(true);
